﻿<template>
  <s-layout class="wallet-wrap" title="钱包">
    <view class="header-container">
      <view class="card-box">
        <view class="card-content">
          <view class="balance-info">
            <view class="balance-label">
              <text class="label-text">钱包余额</text>
              <view
                @tap="changeShow"
                class="eye-icon"
                :class="state.showMoney ? 'cicon-eye' : 'cicon-eye-off'"
              ></view>
            </view>
            <view class="balance-amount">
              <text class="currency">¥</text>
              <text class="amount">{{
                state.showMoney ? state.currentBalance || "0.00" : "****"
              }}</text>
              <view
                class="mini-withdrawal-btn"
                @tap="showWithdrawalModal"
                v-if="state.showMoney"
              >
                <text class="mini-btn-text">提现</text>
              </view>
            </view>
          </view>
          <view class="stats-info">
            <view class="stat-item">
              <text class="stat-value">{{ state.totalRecords }}</text>
              <text class="stat-label">总笔数</text>
            </view>
            <view class="stat-divider"></view>
            <view class="stat-item">
              <text class="stat-value">{{ state.incomeCount }}</text>
              <text class="stat-label">收入笔数</text>
            </view>
            <view class="stat-divider"></view>
            <view class="stat-item">
              <text class="stat-value">{{ state.outcomeCount }}</text>
              <text class="stat-label">支出笔数</text>
            </view>
          </view>
          <view class="total-balance-info" v-if="state.showMoney">
            <view class="total-balance-label">累计余额</view>
            <view class="total-balance-amount">
              <text class="currency">¥</text>
              <text class="amount">{{ state.totalBalance }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view class="content-section">
      <view class="tab-header">
        <su-tabs
          :list="tabMaps"
          @change="onChangeTab"
          :scrollable="false"
          :current="state.currentTab"
        ></su-tabs>
      </view>

      <view class="records-container">
        <s-empty
          v-if="state.filteredList.length === 0 && !state.loading"
          icon="/static/data-empty.png"
          text="暂无记录"
        ></s-empty>

        <view v-if="state.filteredList.length > 0" class="records-list">
          <view
            class="record-item"
            v-for="item in state.filteredList"
            :key="item.id"
          >
            <view class="record-icon">
              <view class="icon-bg" :class="getRecordClass(item)">
                <text class="icon-text">{{ getIconText(item) }}</text>
              </view>
            </view>
            <view class="record-content">
              <view class="record-main">
                <text class="record-title">{{ getTypeDesc(item) }}</text>
                <view class="record-amount" :class="getRecordClass(item)">
                  <text>{{ getAmountPrefix(item) }}{{ item.amount }}</text>
                </view>
              </view>
              <view class="record-detail">
                <text class="detail-text">{{
                  item.orderId || "系统操作"
                }}</text>
                <text class="record-time">{{
                  formatTime(item.createTime)
                }}</text>
              </view>
            </view>
          </view>
        </view>

        <uni-load-more
          v-if="state.filteredList.length > 0"
          :status="state.loadStatus"
          :content-text="{
            contentdown: '已加载全部',
            contentnomore: '没有更多了',
          }"
        />
      </view>
    </view>

    <uni-popup
      ref="withdrawalPopup"
      type="center"
      background-color="rgba(0,0,0,0.6)"
    >
      <view class="withdrawal-modal">
        <view class="modal-header">
          <view class="header-content">
            <text class="modal-icon">💰</text>
            <text class="modal-title">申请提现</text>
          </view>
          <view class="close-btn" @tap="hideWithdrawalModal">
            <text class="close-icon">✕</text>
          </view>
        </view>

        <view class="modal-content">
          <view class="balance-card">
            <view class="card-title">
              <text>当前可提现余额</text>
            </view>
            <view class="balance-amount">
              <text class="currency">¥</text>
              <text class="amount">{{ state.currentBalance }}</text>
            </view>
          </view>

          <view class="tips-section">
            <view class="tip-item">
              <text class="tip-text"
                >最低提现金额：¥{{ minWithdrawAmount }}</text
              >
            </view>
          </view>

          <view class="input-section">
            <view class="input-label">
              <text>提现金额</text>
            </view>
            <view
              class="input-wrapper"
              :class="{ error: state.withdrawalError }"
            >
              <text class="currency-symbol">¥</text>
              <input
                class="amount-input"
                type="digit"
                placeholder="请输入提现金额"
                v-model="state.withdrawalAmount"
                @input="onAmountInput"
              />
            </view>
            <view class="quick-amounts">
              <view
                class="quick-amount-btn"
                v-for="amount in getQuickAmounts()"
                :key="amount"
                @tap="selectQuickAmount(amount)"
              >
                <text>{{ amount }}元</text>
              </view>
              <view class="quick-amount-btn all-btn" @tap="selectAllAmount">
                <text>全部</text>
              </view>
            </view>
            <view class="error-tip" v-if="state.withdrawalError">
              <text class="error-icon">⚠️</text>
              <text class="error-text">{{ state.withdrawalError }}</text>
            </view>
          </view>
        </view>

        <view class="modal-footer">
          <button class="cancel-btn" @tap="hideWithdrawalModal">
            <text>取消</text>
          </button>
          <button
            class="confirm-btn"
            @tap="confirmWithdrawal"
            :disabled="!canWithdraw"
            :class="{ loading: state.withdrawing }"
          >
            <text v-if="!state.withdrawing">立即提现</text>
            <text v-else>处理中...</text>
          </button>
        </view>
      </view>
    </uni-popup>
  </s-layout>
</template>

<script setup>
import { computed, reactive, ref } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import sheep from "@/sheep";
import dayjs from "dayjs";

const withdrawalPopup = ref(null);

function changeShow() {
  state.showMoney = !state.showMoney;
  uni.setStorageSync("showMoney", state.showMoney);
}

const state = reactive({
  showMoney:
    uni.getStorageSync("showMoney") === ""
      ? true
      : uni.getStorageSync("showMoney"),
  currentTab: 0,
  currentBalance: "0.00",
  totalBalance: "0.00",
  historyList: [],
  filteredList: [],
  loadStatus: "noMore",
  loading: false,
  totalRecords: 0,
  incomeCount: 0,
  outcomeCount: 0,
  withdrawalAmount: "",
  withdrawalError: "",
  withdrawing: false,
});

const minWithdrawAmount = ref("");

const tabMaps = [
  {
    name: "全部",
    value: 0,
  },
  {
    name: "收入",
    value: 1,
  },
  {
    name: "支出",
    value: 2,
  },
];

const canWithdraw = computed(() => {
  const amount = parseFloat(state.withdrawalAmount);
  const balance = parseFloat(state.currentBalance);
  const minAmount = parseFloat(minWithdrawAmount.value || 0);

  return (
    !state.withdrawing &&
    !isNaN(amount) &&
    amount > 0 &&
    amount >= minAmount &&
    amount <= balance &&
    !state.withdrawalError
  );
});

async function getWalletConfig() {
  try {
    const response = await sheep.$api.data.wallet.config();
    if (response) {
      minWithdrawAmount.value = response;
    }
  } catch (error) {
  }
}

async function getWalletStat() {
  try {
    const stat = await sheep.$api.data.wallet.stat();
    if (stat) {
      state.currentBalance = (stat.balance || 0).toFixed(2);
      state.totalBalance = (stat.totalBalance || 0).toFixed(2);
      state.totalRecords = stat.totalCount || 0;
      state.incomeCount = stat.inCount || 0;
      state.outcomeCount = stat.outCount || 0;
    }
  } catch (error) {
  }
}

async function getWalletHistory() {
  try {
    state.loading = true;
    state.loadStatus = "loading";

    const currentTab = tabMaps[state.currentTab];
    let type;

    if (currentTab.value === 0) {
      type = 0;
    } else if (currentTab.value === 1) {
      type = "1";
    } else if (currentTab.value === 2) {
      type = "2";
    }

    const data = await sheep.$api.data.wallet.list(type);

    if (data && Array.isArray(data)) {
      state.historyList = data;
      state.filteredList = data;
    } else {
      state.historyList = [];
      state.filteredList = [];
    }

    state.loadStatus = "noMore";
  } catch (error) {
    state.loadStatus = "noMore";
    state.historyList = [];
    state.filteredList = [];
  } finally {
    state.loading = false;
  }
}

function getRecordClass(item) {
  switch (item.subOpType) {
    case 21:
    case 22:
      return "income";
    case 31:
      return "outcome";
    default:
      return item.opType === 1 ? "income" : "outcome";
  }
}

function getAmountPrefix(item) {
  switch (item.subOpType) {
    case 21:
    case 22:
      return "+";
    case 31:
      return "-";
    default:
      return item.opType === 1 ? "+" : "-";
  }
}

function getIconText(item) {
  switch (item.subOpType) {
    case 21:
      return "返";
    case 22:
      return "返";
    case 31:
      return "提";
    default:
      switch (item.opType) {
        case 1:
          return "收";
        case 2:
          return "返";
        case 3:
          return "其";
        default:
          return "记";
      }
  }
}

function getTypeDesc(item) {
  switch (item.subOpType) {
    case 21:
      return "充值返点";
    case 22:
      return "消费返点";
    case 31:
      return "提现支出";
    default:
      switch (item.opType) {
        case 1:
          switch (item.subOpType) {
            case 11:
              return "余额充值";
            default:
              return "收入";
          }
        case 2:
          return "返点";
        case 3:
          return "其他";
        default:
          return "未知类型";
      }
  }
}

function formatTime(timeStr) {
  if (!timeStr) return "";
  return dayjs(timeStr).format("MM-DD HH:mm");
}

function checkWechatSupport() {
  return uni.canIUse("requestMerchantTransfer");
}

function getQuickAmounts() {
  const balance = parseFloat(state.currentBalance) || 0;
  const amounts = [50, 100, 200, 500];
  return amounts.filter((amount) => amount <= balance);
}

function selectQuickAmount(amount) {
  state.withdrawalAmount = amount.toString();
  validateWithdrawalAmount();
}

function selectAllAmount() {
  state.withdrawalAmount = state.currentBalance;
  validateWithdrawalAmount();
}

function showWithdrawalModal() {
  if (!checkWechatSupport()) {
    uni.showToast({
      title: "当前微信版本不支持提现功能",
      icon: "none",
      duration: 2000,
    });
    return;
  }

  state.withdrawalAmount = "";
  state.withdrawalError = "";
  withdrawalPopup.value.open();
}

function hideWithdrawalModal() {
  withdrawalPopup.value.close();
}

function onAmountInput(e) {
  const value = e.detail.value;
  state.withdrawalAmount = value;
  validateWithdrawalAmount();
}

function validateWithdrawalAmount() {
  const amount = parseFloat(state.withdrawalAmount);
  const balance = parseFloat(state.currentBalance);
  const minAmount = parseFloat(minWithdrawAmount.value || 0);

  state.withdrawalError = "";

  if (isNaN(amount) || amount <= 0) {
    state.withdrawalError = "请输入有效的提现金额";
    return false;
  }

  if (minAmount > 0 && amount < minAmount) {
    state.withdrawalError = `提现金额不能少于${minAmount}元`;
    return false;
  }

  if (amount > balance) {
    state.withdrawalError = "提现金额不能超过账户余额";
    return false;
  }

  return true;
}

function requestMerchantTransfer(data) {
  return new Promise((resolve, reject) => {
    uni.requestMerchantTransfer({
      mchId: "1619306404",
      appId: "wx0f7bfde8fd94933d",
      package: data.packageInfo,
      success: (res) => {
        resolve(res);
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
}

async function confirmWithdrawal() {
  if (!validateWithdrawalAmount()) {
    return;
  }

  try {
    state.withdrawing = true;

    const result = await sheep.$api.data.wallet.withdrawal({
      amount: parseFloat(state.withdrawalAmount),
    });

    if (result && result.packageInfo) {
      await requestMerchantTransfer(result);

      uni.showToast({
        title: "提现成功",
        icon: "success",
      });

      hideWithdrawalModal();
      await Promise.all([getWalletStat(), getWalletHistory()]);
    } else {
      throw new Error("提现参数获取失败");
    }
  } catch (error) {
    uni.showToast({
      title: "服务器繁忙",
      icon: "error",
      duration: 2000,
    });
  } finally {
    state.withdrawing = false;
  }
}

function onChangeTab(e) {
  state.currentTab = e.index;
  getWalletHistory();
}

onLoad(async (options) => {
  await Promise.all([getWalletConfig(), getWalletStat(), getWalletHistory()]);
});
</script>

<style lang="scss" scoped>
.header-container {
  padding: 30rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

  .card-box {
    background: rgba(255, 255, 255, 0.15);
    backdrop-filter: blur(20rpx);
    border-radius: 24rpx;
    padding: 40rpx;
    border: 1rpx solid rgba(255, 255, 255, 0.2);

    .card-content {
      .balance-info {
        margin-bottom: 40rpx;

        .balance-label {
          display: flex;
          align-items: center;
          margin-bottom: 20rpx;

          .label-text {
            font-size: 28rpx;
            color: rgba(255, 255, 255, 0.9);
            margin-right: 16rpx;
          }

          .eye-icon {
            font-size: 32rpx;
            color: rgba(255, 255, 255, 0.8);
          }
        }

        .balance-amount {
          display: flex;
          align-items: baseline;

          .currency {
            font-size: 32rpx;
            color: white;
            margin-right: 28rpx;
          }

          .amount {
            font-size: 48rpx;
            font-weight: 600;
            color: white;
            font-family: OPPOSANS;
            margin-right: 8rpx;
          }

          .mini-withdrawal-btn {
            width: 100rpx;
            background: transparent;
            border: none;
            padding: 8rpx 16rpx;
            font-size: 24rpx;
            color: rgba(255, 255, 255, 0.9);

            .mini-btn-text {
              font-size: 24rpx;
              font-weight: 500;
              color: rgba(255, 255, 255, 0.9);
              text-decoration: none;
            }
          }
        }
      }

      .stats-info {
        display: flex;
        align-items: center;
        justify-content: space-around;

        .stat-item {
          display: flex;
          flex-direction: column;
          align-items: center;

          .stat-value {
            font-size: 32rpx;
            font-weight: 600;
            color: white;
            margin-bottom: 8rpx;
          }

          .stat-label {
            font-size: 24rpx;
            color: rgba(255, 255, 255, 0.8);
          }
        }

        .stat-divider {
          width: 1rpx;
          height: 60rpx;
          background: rgba(255, 255, 255, 0.3);
        }
      }

      .total-balance-info {
        margin-top: 30rpx;
        padding-top: 24rpx;
        border-top: 1rpx solid rgba(255, 255, 255, 0.2);
        text-align: center;

        .total-balance-label {
          font-size: 24rpx;
          color: rgba(255, 255, 255, 0.8);
          margin-bottom: 12rpx;
        }

        .total-balance-amount {
          display: flex;
          align-items: baseline;
          justify-content: center;

          .currency {
            font-size: 28rpx;
            color: rgba(255, 255, 255, 0.9);
            margin-right: 6rpx;
          }

          .amount {
            font-size: 36rpx;
            font-weight: 600;
            color: white;
            font-family: OPPOSANS;
          }
        }
      }
    }
  }
}

.content-section {
  background: #f8f9fa;
  min-height: calc(100vh - 300rpx);

  .tab-header {
    background: white;
    padding: 0 30rpx;
    border-bottom: 1rpx solid #f0f0f0;
  }

  .records-container {
    padding: 20rpx 30rpx;

    .records-list {
      .record-item {
        background: white;
        border-radius: 16rpx;
        padding: 24rpx;
        margin-bottom: 16rpx;
        display: flex;
        align-items: flex-start;
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

        .record-icon {
          margin-right: 24rpx;

          .icon-bg {
            width: 80rpx;
            height: 80rpx;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;

            &.income {
              background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            }

            &.outcome {
              background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
            }

            .icon-text {
              font-size: 32rpx;
              font-weight: 600;
              color: white;
            }
          }
        }

        .record-content {
          flex: 1;

          .record-main {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12rpx;

            .record-title {
              font-size: 32rpx;
              font-weight: 500;
              color: #333;
            }

            .record-amount {
              font-size: 32rpx;
              font-weight: 600;
              font-family: OPPOSANS;

              &.income {
                color: #52c41a;
              }

              &.outcome {
                color: #ff4d4f;
              }
            }
          }

          .record-detail {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .detail-text {
              font-size: 26rpx;
              color: #666;
              flex: 1;
              margin-right: 20rpx;
            }

            .record-time {
              font-size: 24rpx;
              color: #999;
            }
          }
        }
      }
    }
  }
}

.withdrawal-modal {
  width: 680rpx;
  background: white;
  border-radius: 32rpx;
  overflow: hidden;
  box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.15);

  .modal-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    padding: 40rpx 32rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .header-content {
      display: flex;
      align-items: center;

      .modal-icon {
        font-size: 36rpx;
        margin-right: 16rpx;
      }

      .modal-title {
        font-size: 36rpx;
        font-weight: 600;
        color: white;
      }
    }

    .close-btn {
      width: 56rpx;
      height: 56rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      background: rgba(255, 255, 255, 0.1);
      border-radius: 50%;

      .close-icon {
        color: white;
        font-size: 28rpx;
        font-weight: bold;
      }
    }
  }

  .modal-content {
    padding: 40rpx 32rpx;

    .balance-card {
      background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
      border-radius: 20rpx;
      padding: 32rpx;
      margin-bottom: 32rpx;

      .card-title {
        display: flex;
        align-items: center;
        margin-bottom: 20rpx;

        .card-icon {
          font-size: 28rpx;
          margin-right: 12rpx;
        }

        text {
          font-size: 28rpx;
          color: #666;
        }
      }

      .balance-amount {
        display: flex;
        align-items: baseline;

        .currency {
          font-size: 28rpx;
          color: #333;
          margin-right: 8rpx;
        }

        .amount {
          font-size: 48rpx;
          font-weight: 700;
          color: #333;
          font-family: "DIN Alternate", -apple-system, sans-serif;
        }
      }
    }

    .tips-section {
      margin-bottom: 32rpx;

      .tip-item {
        display: flex;
        align-items: center;
        margin-bottom: 16rpx;

        .tip-icon {
          font-size: 24rpx;
          margin-right: 12rpx;
        }

        .tip-text {
          font-size: 26rpx;
          color: #666;
        }
      }
    }

    .input-section {
      .input-label {
        font-size: 30rpx;
        color: #333;
        margin-bottom: 20rpx;
        font-weight: 600;
      }

      .input-wrapper {
        display: flex;
        align-items: center;
        border: 3rpx solid #e6e6e6;
        border-radius: 16rpx;
        padding: 24rpx;
        background: #fafafa;
        transition: all 0.3s ease;

        &.error {
          border-color: #ff4d4f;
          background: #fff2f0;
        }

        &:focus-within {
          border-color: #667eea;
          background: white;
          box-shadow: 0 0 0 6rpx rgba(102, 126, 234, 0.1);
        }

        .currency-symbol {
          font-size: 36rpx;
          color: #333;
          margin-right: 12rpx;
          font-weight: 600;
        }

        .amount-input {
          flex: 1;
          font-size: 36rpx;
          color: #333;
          border: none;
          outline: none;
          background: transparent;
          font-weight: 600;
          font-family: "DIN Alternate", -apple-system, sans-serif;
        }
      }

      .quick-amounts {
        display: flex;
        flex-wrap: wrap;
        gap: 16rpx;
        margin: 24rpx 0;

        .quick-amount-btn {
          flex: 1;
          min-width: 120rpx;
          height: 64rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          background: #f8f9fa;
          border: 2rpx solid #e9ecef;
          border-radius: 32rpx;
          font-size: 26rpx;
          color: #666;
          transition: all 0.3s ease;

          &:active {
            transform: scale(0.95);
          }

          &.all-btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-color: transparent;
          }

          text {
            font-size: 26rpx;
            font-weight: 500;
          }
        }
      }

      .error-tip {
        margin-top: 16rpx;
        display: flex;
        align-items: center;
        padding: 12rpx 16rpx;
        background: #fff2f0;
        border-radius: 8rpx;

        .error-icon {
          font-size: 24rpx;
          margin-right: 8rpx;
        }

        .error-text {
          font-size: 24rpx;
          color: #ff4d4f;
        }
      }
    }
  }

  .modal-footer {
    display: flex;
    padding: 24rpx 32rpx 32rpx;
    gap: 20rpx;

    .cancel-btn,
    .confirm-btn {
      flex: 1;
      height: 88rpx;
      border: none;
      border-radius: 24rpx;
      font-size: 30rpx;
      font-weight: 600;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.3s ease;

      &:active {
        transform: scale(0.95);
      }
    }

    .cancel-btn {
      background: #f8f9fa;
      color: #666;
      border: 2rpx solid #e9ecef;
    }

    .confirm-btn {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.3);

      &:disabled {
        background: #e9ecef;
        color: #adb5bd;
        box-shadow: none;
        cursor: not-allowed;
      }

      &.loading {
        background: #ced4da;
        color: #6c757d;
      }
    }
  }
}
</style>
